<template>
  <div class="trend-full">
    <div class="toolbar">
      <el-button @click="goBack" type="default" size="small">返回</el-button>
      <el-divider direction="vertical" />
      <el-radio-group v-model="period" size="small">
        <el-radio-button label="month">按月</el-radio-button>
        <el-radio-button label="week">按周</el-radio-button>
      </el-radio-group>
      <el-divider direction="vertical" />
      <el-radio-group v-model="chartType" size="small">
        <el-radio-button label="line">折线</el-radio-button>
        <el-radio-button label="stacked">堆叠柱</el-radio-button>
      </el-radio-group>
    </div>

    <div class="chart-wrap">
      <v-chart class="chart" :option="option" autoresize />
    </div>
    <div class="chart-tip">说明：红色圈圈代表该型号在此时间为峰值</div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAnrStore } from '../stores/anr'
import { storeToRefs } from 'pinia'

const router = useRouter()
const anrStore = useAnrStore()
const { modelTrendData, modelTrendPeriod } = storeToRefs(anrStore)
const { setModelTrendPeriod } = anrStore

const chartType = ref('line')
const period = computed({
  get: () => modelTrendPeriod.value,
  set: v => setModelTrendPeriod(v)
})

const goBack = () => router.back()

function buildSeriesWithPeakOffsets(data) {
  const xAxis = data.xAxis || []
  const series = (data.series || []).map(s => ({ ...s }))
  const peaksByLabel = new Map()
  series.forEach((s, si) => {
    const arr = Array.isArray(s.data) ? s.data.map(v => Number(v) || 0) : []
    if (!arr.length) return
    const maxVal = Math.max(...arr)
    const idx = arr.findIndex(v => v === maxVal)
    if (idx < 0) return
    const label = xAxis[idx]
    if (!peaksByLabel.has(label)) peaksByLabel.set(label, [])
    peaksByLabel.get(label).push({ si, idx, val: maxVal, label })
  })
  peaksByLabel.forEach(list => {
    list.sort((a, b) => a.si - b.si)
    list.forEach((p, order) => {
      const s = series[p.si]
      const yOffset = -14 * order
      const labelDist = 8 + order * 2
      s.markPoint = {
        symbol: 'circle',
        symbolSize: 12,
        symbolOffset: [0, yOffset],
        itemStyle: { color: '#d90000' },
        label: { show: true, formatter: '{c}', position: 'top', distance: labelDist, color: '#d90000', fontSize: 11 },
        data: [ { name: '峰值', value: p.val, coord: [xAxis[p.idx], p.val] } ]
      }
    })
  })
  return series
}

// ISO 周(YYYY-WW) → 标签 "M月D- M月D"
function isoWeekLabelToRangeLabel(isoWeek) {
  const m = /^(\d{4})-(\d{2})$/.exec(String(isoWeek))
  if (!m) return String(isoWeek)
  const year = Number(m[1])
  const week = Number(m[2])
  const jan4 = new Date(Date.UTC(year, 0, 4))
  const jan4Dow = jan4.getUTCDay() === 0 ? 7 : jan4.getUTCDay()
  const monday = new Date(jan4)
  monday.setUTCDate(jan4.getUTCDate() - (jan4Dow - 1) + (week - 1) * 7)
  const sunday = new Date(monday)
  sunday.setUTCDate(monday.getUTCDate() + 6)
  const fmt = (d) => `${d.getUTCMonth() + 1}月${d.getUTCDate()}`
  return `${fmt(monday)}-${fmt(sunday)}`
}

const displayXAxis = computed(() => {
  const raw = (modelTrendData.value && modelTrendData.value.xAxis) || []
  return period.value === 'week' ? raw.map(isoWeekLabelToRangeLabel) : raw
})

const option = computed(() => {
  const data = modelTrendData.value || { legend: [], xAxis: [], series: [] }
  const baseSeries = (data.series || []).map(s => ({
    ...s,
    type: chartType.value === 'stacked' ? 'bar' : 'line',
    stack: chartType.value === 'stacked' ? 'total' : undefined,
    large: true,
    smooth: chartType.value === 'line',
    emphasis: { focus: 'series' }
  }))
  const series = buildSeriesWithPeakOffsets({ ...data, xAxis: displayXAxis.value, series: baseSeries })
  return {
    tooltip: { trigger: 'axis', axisPointer: { type: chartType.value === 'stacked' ? 'shadow' : 'cross' } },
    legend: { type: 'scroll', top: 10, data: data.legend || [] },
    grid: { left: 40, right: 40, top: 60, bottom: 60, containLabel: true },
    xAxis: { type: 'category', boundaryGap: chartType.value === 'stacked', data: displayXAxis.value },
    yAxis: { type: 'value' },
    dataZoom: [
      { type: 'inside', xAxisIndex: 0, filterMode: 'none' },
      { type: 'slider', xAxisIndex: 0, bottom: 10 }
    ],
    series
  }
})
</script>

<style scoped>
.trend-full { height: 100vh; width: 100vw; display: flex; flex-direction: column; }
.toolbar { padding: 12px 16px; display: flex; align-items: center; gap: 8px; border-bottom: 1px solid #f0f0f0; }
.chart-wrap { flex: 1; width: 100%; height: calc(100vh - 84px); padding: 8px 16px; }
.chart { width: 100%; height: 100%; }
.chart-tip { padding: 0 16px 12px; font-size: 12px; color: #909399; }
</style>
